import { createAlova } from 'alova'
import { notification } from 'antd'
import ReactHook from 'alova/react'
import adapterFetch from 'alova/fetch'

import { GetIndexedDB } from './IndexedDB'
import { ContentTypeMapping } from '../Config/theme'

const common = 'https://common-api.ljkjkf.com/'
const AdminA06 = 'https://mock.presstime.cn/mock/67529e495750db2bfa55e183/jiantou/'
const Api = 'https://jiantou-rest.ljkjkf.com/'
// const Api = 'https://ceshi-rest.ljkjkf.com/'

export const API_LIST = (path = []) => {
    // const { AUTH, API } = window
    return {
        getAdminA06ProjectConfig: `${AdminA06}ProjectConfig`,
        // getMenuConfig: `${AdminA06}getMenuConfig`,

        // token
        getListByUser: `${Api}users/GetOrganizationListByUser`,
        posToken: `${Api}authLogin/Login`,

        // JSON
        getJSONData: `${Api}dictionary/GetJsonInfoByUuid`,
        posJSONData: `${Api}dictionary/SaveJsonInfoByUuid`,
        getJSONList: `${Api}dictionary/GetFileNameByPathAndContent`,

        // Attachments
        getAttachment: `${Api}attachments`,
        getAttachmentFile: `${Api}attachments/GetAttachmentFile`,
        getAttachmentDetail: `${Api}attachments/GetAttachmentDetail`,
        posAttachment: `${Api}attachments`,
        posAttachmentBase64: `${Api}attachments/UploadBase64Image`,
        posAttachmentAddAtt: `${Api}attachments/AddAttachmentDetail`,

        delAttachment: `${Api}attachments`,
        posAttachmentRemoveAttachmentByUuid: `${Api}attachments/RemoveAttachmentByUuid`,

        // DictionaryType
        getDictionaryType: `${Api}dictionaryType`,
        posDictionaryType: `${Api}dictionaryType`,
        putDictionaryType: `${Api}dictionaryType`,
        delDictionaryType: `${Api}dictionaryType`,
        // Dictionary
        getDictionary: `${Api}dictionary`,
        posDictionary: `${Api}dictionary`,
        putDictionary: `${Api}dictionary`,
        delDictionary: `${Api}dictionary`,

        // Menu
        getMenu: `${Api}menu`,
        posMenu: `${Api}menu`,
        putMenu: `${Api}menu`,
        delMenu: `${Api}menu`,
        getMenuColumnList: `${Api}menu/GetMenuColumnList`,

        // Role
        getRole: `${Api}role`,
        posRole: `${Api}role`,
        putRole: `${Api}role`,
        delRole: `${Api}role`,
        getRoleDetail: `${Api}role/GetRoleDetail`,
        posRoleUser: `${Api}roleUser`,
        getRoleMenu: `${Api}roleMenu`,
        posRoleMenu: `${Api}roleMenu`,
        getRoleMenuListByRole: `${Api}roleMenu/GetRoleMenuListByRole`,
        getRoleMenuListByUserUuid: `${Api}roleMenu/GetRoleMenuListByUserUuid`,

        getRoleUserUuidByRoleUuid: `${Api}roleUser/GetUserUuidByRoleUuid`,
        posRoleBatchAddRoleUser: `${Api}roleUser/BatchAddRoleUser`,



        posRoleUserAddRoleUserNew: `${Api}roleUser/AddRoleUserNew`,

        // Organization
        getOrganization: `${Api}organization`,
        posOrganization: `${Api}organization`,
        putOrganization: `${Api}organization`,
        delOrganization: `${Api}organization`,
        posOrganizationReport: `${Api}organization/UpdateOrganizationReport`,
        getOrganizationTree: `${Api}organization/GetOrganizationTree`,
        posOrganizationLock: `${Api}organization/BatchLock`,
        posUpdateOrganizationReportType: `${Api}organization/UpdateOrganizationReportType`,

        // EnterpriseQualifications
        getEnterpriseQualifications: `${Api}enterpriseQualifications`,
        posEnterpriseQualifications: `${Api}enterpriseQualifications`,
        putEnterpriseQualifications: `${Api}enterpriseQualifications`,
        delEnterpriseQualifications: `${Api}enterpriseQualifications`,
        getEnterpriseQualificationsTwo: `${Api}enterpriseQualifications/GetEnterpriseQualifications`,

        // Users
        getUsers: `${Api}users`,
        posUsers: `${Api}users`,
        putUsers: `${Api}users`,
        delUsers: `${Api}users`,
        getUserManageProject: `${Api}userManageProject`,
        posUserManageProject: `${Api}userManageProject`,
        getUserInfo: `${Api}users/GetUserInfo`,
        getUserListByOrganizationUuid: `${Api}users/GetUserListByOrganizationUuid`,
        getUserUuidByProjectUuid: `${Api}userManageProject/GetUserUuidByProjectUuid`,
        posUsersAddUserManageProject: `${Api}userManageProject/AddUserManageProject`,
        posUsersChangePassword: `${Api}users/changePassword`,
        posUsersResetPassword: `${Api}users/ResetPassword`,
        getUserLogList: `${Api}users/GetUserLogList`,

        getFlowTreeList: `${Api}users/GetFlowTreeList`,
        getUserListByFlowUuid: `${Api}users/GetUserListByFlowUuid`,
        posUsersAddFlowUser: `${Api}users/AddFlowUser`,
        posUsersBatchRemoveFlowUser: `${Api}users/BatchRemoveFlowUser`,

        // wx
        posUsersBindOpenWeChatUnionId: `${Api}users/BindOpenWeChatUnionId`,
        getUsersGetOpenUnionidOrTokenSSE: `${Api}users/GetOpenUnionidOrTokenSSE`,
        posUsersBindOpenWeChatUnionIdAndUserId: `${Api}users/BindOpenWeChatUnionIdAndUserId`,
        posUsersUnBindOpenWeChatUnionId: `${Api}users/UnBindOpenWeChatUnionId`,
        getCommonGetOpenUnionidOrTokenSSE: `${common}wechatProjects/GetOpenUnionidOrTokenSSE`,

        // ProjectInfo
        getProjectInfo: `${Api}projectInfo`,
        posProjectInfo: `${Api}projectInfo`,
        putProjectInfo: `${Api}projectInfo`,
        delProjectInfo: `${Api}projectInfo`,
        getProjectInfoGetExcelTemp: `${Api}projectInfo/GetExcelTemp`,
        getProjectInfoGetBidQualificationList: `${Api}projectInfo/GetBidQualificationList`,
        posProjectInfoUploadExcel: `${Api}projectInfo/UploadExcel`,
        posProjectInfoBatchRemove: `${Api}projectInfo/BatchRemove`,
        posProjectInfoBatchSubmitInfo: `${Api}projectInfo/BatchSubmitInfo`,
        getProjectInfoOLAP: `${Api}projectInfo/GetProjectInfoOLAP`,

        posGetBatchExcelTemp: `${Api}projectInfo/GetBatchExcelTemp`,
        posUploadExcel: `${Api}projectInfo/UploadExcel`,


        // CostMonthDetailInfo
        getCostMonthDetailInfo: `${Api}costMonthDetailInfo`,
        posCostMonthDetailInfoBatchRemove: `${Api}costMonthDetailInfo/BatchRemove`,
        posCostMonthDetailInfoBatchSubmitInfo: `${Api}costMonthDetailInfo/BatchSubmitInfo`,
        getCostMonthDetailInfoAcross: `${Api}costMonthDetailInfo/GetCostMonthDetailAcross`,
        getCostMonthDetailInfoUpdate: `${Api}costMonthDetailInfo/GetUpdateProjectInfo`,
        posCostMonthDetailInfoUpload: `${Api}costMonthDetailInfo/UploadCostMonthDetailAcross`,
        getCostMonthDetailInfoProjectDetailReportPDF: `${Api}costMonthDetailInfo/GetProjectDetailReportPDF`,
        getCostMonthDetailInfoOLAP: `${Api}costMonthDetailInfo/GetProjectDetailOLAP`,
        getApprovalProjectDetail: `${Api}costMonthDetailInfo/GetApprovalProjectDetail`,
        posBatchApprovalProject: `${Api}costMonthDetailInfo/BatchApprovalProject`,
        getApprovalDetail: `${Api}costMonthDetailInfo/GetApprovalDetail`,
        getProjectDetail: `${Api}costMonthDetailInfo/GetProjectDetail`,
        getProjectDetailExcel: `${Api}costMonthDetailInfo/GetProjectDetailExcel`,

        // costMonth
        getCostMonth: `${Api}costMonth`,
        posCostMonth: `${Api}costMonth`,
        putCostMonth: `${Api}costMonth`,
        delCostMonth: `${Api}costMonth`,
        getCostMonthDetailCompanyExcel: `${Api}costMonth/GetCostMonthDetailCompanyExcel`,
        posCostMonthUploadCostMonthDetailCompany: `${Api}costMonth/UploadCostMonthDetailCompany`,
        posCostMonthBatchRemove: `${Api}costMonth/BatchRemove`,
        posCostMonthBatchSubmitInfo: `${Api}costMonth/BatchSubmitInfo`,
        getCostMonthCompanyReportPDF: `${Api}costMonth/GetCompanyReportPDF`,
        getCostMonthCompanyReportPDFNo: `${Api}costMonth/GetCompanyReportPDFNo`,

        getCostMonthOLAP: `${Api}costMonth/GetCostMonthOLAP`,
        getCostMonthDetails: `${Api}costMonth/GetCostMonthDetails`,
        getCostMonthGetAuditTableList: `${Api}costMonth/GetAuditTableList`,
        getCostMonthApprovalDetail: `${Api}costMonth/GetApprovalDetail`,
        posCostMonthBatchAuditTable: `${Api}costMonth/BatchAuditTable`,
        getScreenManageList: `${Api}costMonth/GetScreenManageList`,
        getScreenManageCompanyList: `${Api}costMonth/GetScreenManageCompanyList`,
        getScreenOperateCompanyList: `${Api}costMonth/GetScreenOperateCompanyList`,
        getScreenOperateProvinceList: `${Api}costMonth/GetScreenOperateProvinceList`,
        getScreenOperateProvinceCompanyList: `${Api}costMonth/GetScreenOperateProvinceCompanyList`,
        getCostMonthGetUnregisteredList: `${Api}costMonth/GetUnregisteredList`,

        posCostMonthBatchLock: `${Api}costMonth/BatchLock`,

        getScreenManageYearMonth: `${Api}costMonth/GetScreenManageYearMonth`,




        // PrebidProjectInfo  8
        getPrebidProjectInfo: `${Api}prebidProjectInfo`,
        posPrebidProjectInfo: `${Api}prebidProjectInfo`,
        putPrebidProjectInfo: `${Api}prebidProjectInfo`,
        delPrebidProjectInfo: `${Api}prebidProjectInfo`,
        getPrebidProjectInfoExcel: `${Api}prebidProjectInfo/GetExcelTemp`,
        posPrebidProjectInfoExcel: `${Api}prebidProjectInfo/UploadExcel`,
        getPrebidProjectInfoOLAP: `${Api}prebidProjectInfo/GetPrebidProjectInfoOLAP`,
        getPrebidProjectInfoDetails: `${Api}prebidProjectInfo/GetPrebidProjectInfoDetails`,
        getPrebidProjectInfoWarningDetails: `${Api}prebidProjectInfo/GetPrebidProjectWarningDetails`,
        posPrebidProjectInfoBatchRemove: `${Api}prebidProjectInfo/BatchRemove`,
        posPrebidProjectInfoBatchSubmitInfo: `${Api}prebidProjectInfo/BatchSubmitInfo`,
        posPrebidProjectInfoBatchApprovalInfo: `${Api}prebidProjectInfo/BatchApprovalInfo`,
        getprebidProjectInfoApprovalList: `${Api}prebidProjectInfo/GetprebidProjectInfoApprovalList`,




        // TrackingProjectManagement  12
        getTrackingProjectManagement: `${Api}trackingProjectManagement`,
        posTrackingProjectManagement: `${Api}trackingProjectManagement`,
        putTrackingProjectManagement: `${Api}trackingProjectManagement`,
        delTrackingProjectManagement: `${Api}trackingProjectManagement`,
        getTrackingProjectManagementExcel: `${Api}trackingProjectManagement/GetExcelTemp`,
        posTrackingProjectManagementExcel: `${Api}trackingProjectManagement/UploadExcel`,
        getTrackingProjectManagementOLAP: `${Api}trackingProjectManagement/GetTrackingProjectManagementOLAP`,
        getTrackingProjectManagementDetails: `${Api}trackingProjectManagement/GetTrackingProjectManagementDetails`,
        getTrackingProjectManagementWarningDetails: `${Api}trackingProjectManagement/GetTrackingProjectWarningDetails`,
        posTrackingProjectManagementBatchRemove: `${Api}trackingProjectManagement/BatchRemove`,
        posTrackingProjectManagementBatchSubmitInfo: `${Api}trackingProjectManagement/BatchSubmitInfo`,
        getTrackingProjectManagementApprovalList: `${Api}trackingProjectManagement/GetTrackingProjectManagementApprovalList`,
        posTrackingProjectManagementBatchApprovalInfo: `${Api}trackingProjectManagement/BatchApprovalInfo`,

        // ContractOrder  13
        getContractOrder: `${Api}contractOrder`,
        posContractOrder: `${Api}contractOrder`,
        putContractOrder: `${Api}contractOrder`,
        delContractOrder: `${Api}contractOrder`,
        getContractOrderExcel: `${Api}contractOrder/GetExcelTemp`,
        posContractOrderExcel: `${Api}contractOrder/UploadExcel`,
        getContractOrderOLAP: `${Api}contractOrder/GetContractOrderOLAP`,
        getOrganizationNameOrderOLAP: `${Api}contractOrder/GetOrganizationNameOrderOLAP`,
        getContractOrderDetails: `${Api}contractOrder/GetContractOrderDetails`,
        posContractOrderBatchRemove: `${Api}contractOrder/BatchRemove`,
        posContractOrderBatchSubmitInfo: `${Api}contractOrder/BatchSubmitInfo`,
        getContractOrderApprovalList: `${Api}contractOrder/GetContractOrderApprovalList`,
        posContractOrderBatchApprovalInfo: `${Api}contractOrder/BatchApprovalInfo`,


        // PlanManagement
        getPlanManagement: `${Api}planManagement`,
        posPlanManagement: `${Api}planManagement`,
        putPlanManagement: `${Api}planManagement`,
        delPlanManagement: `${Api}planManagement`,
        posPlanManagementBatchRemove: `${Api}planManagement/BatchRemove`,
        posPlanManagementBatchSubmitInfo: `${Api}planManagement/BatchSubmitInfo`,

        // MigrantWorkerSalaryManagement
        getMigrantWorkerSalaryManagement: `${Api}migrantWorkerSalaryManagement`,
        posMigrantWorkerSalaryManagement: `${Api}migrantWorkerSalaryManagement`,
        putMigrantWorkerSalaryManagement: `${Api}migrantWorkerSalaryManagement`,
        delMigrantWorkerSalaryManagement: `${Api}migrantWorkerSalaryManagement`,

        getMigrantWorkerSalaryManagementGetExcel: `${Api}migrantWorkerSalaryManagement/GetExcelTemp`,
        posMigrantWorkerSalaryManagementPosExcel: `${Api}migrantWorkerSalaryManagement/UploadExcel`,
        posMigrantWorkerSalaryManagementBatchRemove: `${Api}migrantWorkerSalaryManagement/BatchRemove`,
        posMigrantWorkerSalaryManagementBatchSubmitInfo: `${Api}migrantWorkerSalaryManagement/BatchSubmitInfo`,
        getMigrantWorkerSalaryManagementOLAP: `${Api}migrantWorkerSalaryManagement/GetMigrantWorkerSalaryManagementOLAP`,
        getMigrantWorkerSalaryManagementDetails: `${Api}migrantWorkerSalaryManagement/GetMigrantWorkerSalaryManagementDetails`,

    }
}

export const API_Mapping = {
    Menu: async () => {
        const res = await Http({ url: 'getMenu' })
        const data = JSON.parse(JSON.stringify(res.data.list).replace(/uuid/g, 'value').replace(/tableName/g, 'title'))
        return [{ value: '00000000-0000-0000-0000-000000000000', title: '一级菜单' }, ...data]
    },
    Organization: async () => {
        const res = await Http({ url: 'getOrganization' })
        return JSON.parse(JSON.stringify(res.data.list).replace(/uuid/g, 'value').replace(/tableName/g, 'label'))
    },
    Identity: async () => { // 身份
        const res = await Http({ url: 'getDictionary', params: { dictionaryTypeUuid: '13741597-4f51-4fca-8688-a817505b2885' } })
        return JSON.parse(JSON.stringify(res.data.list).replace(/uuid/g, 'value').replace(/tableName/g, 'label'))
    },
    // 字典
    DictionaryType: async () => { // 字典大类
        const res = await Http({ url: 'getDictionaryType' })
        return JSON.parse(JSON.stringify(res.data.list).replace(/uuid/g, 'value').replace(/tableName/g, 'label'))
    },
    CompanyType: async () => { // 公司类型
        const res = await Http({ url: 'getDictionary', params: { dictionaryTypeUuid: '522b8c28-9b85-4198-b65c-1bf4dca46efa' } })
        return JSON.parse(JSON.stringify(res.data.list).replace(/uuid/g, 'value').replace(/tableName/g, 'label'))
    },
    GradeType: async () => { // 资质等级
        const res = await Http({ url: 'getDictionary', params: { dictionaryTypeUuid: '44e0b748-c3c4-48b7-be55-021deffba0eb' } })
        return JSON.parse(JSON.stringify(res.data.list).replace(/uuid/g, 'value').replace(/tableName/g, 'label'))
    }
}

const codeMessage = {
    200: '服务器成功返回请求的数据。',
    201: '新建或修改数据成功。',
    202: '一个请求已经进入后台排队（异步任务）。',
    204: '删除数据成功。',
    400: '系统提示!',
    401: '用户没有权限（令牌、用户名、密码错误）。',
    403: '用户得到授权，但是访问是被禁止的。',
    404: '发出的请求针对的是不存在的记录。',
    406: '请求的格式不可得。',
    410: '请求的资源被永久删除，且不会再得到的。',
    422: '当创建一个对象时，发生一个验证错误。',
    500: '服务器发生错误，请检查服务器。',
    502: '网关错误。',
    503: '服务不可用，服务器暂时过载或维护。',
    504: '网关超时。',
    521: '接口又爱了'
}

const alovaInstance = createAlova({
    localCache: null,
    timeout: 10000,
    statesHook: ReactHook,
    requestAdapter: adapterFetch(),
    cacheFor: false, // 禁用缓存机制

    async beforeRequest(method) {
        const { url } = method
        const TypeXFrom = [
        ]
        const urlsToMatch = [
            API_LIST()['posToken'],
            API_LIST()['getListByUser'],
            API_LIST()['getProjectConfigInfo'],
            API_LIST()['getAdminA06ProjectList'],
            API_LIST()['getAdminA06ProjectConfig'],
            API_LIST()['getJSONData'],
        ]

        if (TypeXFrom.includes(url)) {
            method.config.headers['content-type'] = 'application/x-www-form-urlencoded'
        } else if (urlsToMatch.includes(url)) {
            method.config.headers['content-type'] = 'application/json; charset=utf-8'
        } else {
            const token = await GetIndexedDB('token')
            if (token) { method.config.headers.Authorization = token }
            else {
                throw new Error('请求头失效')
            }
        }
    },
    responded: {
        onSuccess: async (response) => {
            const contentType = response.headers.get('Content-Type')
            if (contentType.indexOf('application/json') !== -1) {
                try {
                    const json = await response.json()
                    if (response.status >= 400) {
                        ErrorModal(response.status, json)
                        throw new Error(json)
                    }
                    return json
                }
                catch (err) {
                    throw new Error(err)
                }
            } else if (ContentTypeMapping.includes(contentType)) {
                try {
                    let filename = '导出文件'
                    const blob = await response.blob()
                    if (response.status >= 400) {
                        ErrorModal(response.status, blob)
                        throw new Error(blob)
                    }
                    const contentDisposition = response.headers.get('Content-Disposition')
                    const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
                    const matches = filenameRegex.exec(contentDisposition)
                    if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '')
                    return { blob, filename, contentType }
                }
                catch (err) {
                    throw new Error(err)
                }
            } else {
                throw new Error('未知响应头')
            }
        },
        onError: (error) => {
            ErrorModal(error)
            throw new Error(err)
        }
        // onComplete: (res) => console.log('[请求完成]', res)
    }
})

export const Http = ({ url, params, path, headers, responseType }) => {
    switch (url.substring(0, 3)) {
        case 'get':
            return alovaInstance.Get(API_LIST(path)[url], { params, headers, responseType })
        case 'pos':
            return alovaInstance.Post(API_LIST(path)[url], params)
        case 'put':
            return alovaInstance.Put(API_LIST(path)[url], params)
        case 'del':
            return alovaInstance.Delete(API_LIST(path)[url], params)
        case 'pat':
            return alovaInstance.Patch(API_LIST(path)[url], params)
        default: return false
    }
}

const ErrorModal = (status, data) => {
    const { message } = data
    notification.error({
        key: 'apiError',
        message: codeMessage[status],
        description: message
    })
}
